package main

import (
	"time"

	_ "gitee.com/XuguDB/go-xugu-driver"
	"xorm.io/xorm"

	//_ "github.com/go-sql-driver/mysql"
	"fmt"
)

type User struct {
	Id      int64     `xorm:"pk autoincr"`
	Name    string    `xorm:"varchar(100)"`
	Age     int       `xorm:"int"`
	Created time.Time `xorm:"created"`
}

func main() {
	engine, err := xorm.NewEngine("xugu", "IP=192.168.2.216;DB=SYSTEM;User=SYSDBA;PWD=SYSDBA;Port=5138;char_set=utf8;")
	if err != nil {
		panic("Failed to connect to database: " + err.Error())
	}
	defer engine.Close()

	//同步结构体到数据库
	err = engine.Sync2(new(User))
	if err != nil {
		panic("Failed to sync database: " + err.Error())
	}
	user := User{
		Name: "张三",
		Age:  25,
	}

	affected, _ := engine.Insert(&user)
	fmt.Printf("插入ID: %d, 影响行数: %d\n", user.Id, affected)

	// ==== 查（Read）====
	// 单条查询
	var u1 User
	has, _ := engine.ID(user.Id).Get(&u1)
	fmt.Printf("查询结果: %+v, 是否存在: %t\n", u1, has)

	// 条件查询
	var u2 User
	has, err = engine.Where("name=?", "张三").Get(&u2)

	// 多条查询
	users := make([]User, 0)
	err = engine.Where("age > ?", 20).Find(&users)
	fmt.Printf("找到 %d 个用户\n", len(users))

	// ==== 改（Update）====
	// 更新单个字段
	affected, err = engine.ID(user.Id).Update(&User{Age: 30})
	fmt.Printf("更新影响行数: %d\n", affected)

	// 更新多个字段
	affected, err = engine.Table(new(User)).ID(user.Id).Update(map[string]interface{}{
		"name": "李四",
		"age":  35,
	})

	// ==== 删（Delete）====
	// 按ID删除
	affected, err = engine.ID(user.Id).Delete(&User{})
	fmt.Printf("删除影响行数: %d\n", affected)

	// 条件删除
	affected, err = engine.Where("age < ?", 18).Delete(&User{})
}
